package cn.ezios.huo.s3.old.file;

import cn.ezios.huo.common.mvc.Ret;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;

@RestController
@RequestMapping("/file/storage")
@RequiredArgsConstructor
public class StorageController {

    private final FileService fileService;

    @Value("${s3.service.static-preview-addr}")
    private String staticPreviewAddr ;

    @GetMapping("preview-addr")
    public Ret previewAddr() {
        return Ret.ok(staticPreviewAddr);
    }

    /**
     * antd组件默认是post请求
     *
     * @param mf
     * @return
     */
    @CrossOrigin
    @PostMapping("/upload-post")
    public Ret uploadPost(@RequestParam("file") MultipartFile mf) {
        String filename = mf.getOriginalFilename();
        long size = mf.getSize();
        try (InputStream inputStream = mf.getInputStream()) {
            S3StorageDTO storageDTO = S3StorageDTO.builder()
                    .inputStream(inputStream)
                    .fileName(filename)
                    .size(size)
                    .build();
            Ret ret = fileService.avatarUpload(storageDTO);
            return ret;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取直链
     */
    @GetMapping("/get-straight-chain/{id}")
    public Ret getUrl(@PathVariable("id") String id) {
        return fileService.getStraightChain(id);
    }

    /**
     * 批量获取直链
     *
     */
    @GetMapping("/get-straight-chain-batch")
    public Ret getUrlBatch(@RequestParam("ids") String ids) {
        if(ids.isBlank()){
            return Ret.error("参数错误");
        }
        String[] idsArr = ids.split(",");
        return fileService.listStraightChain(Arrays.stream(idsArr).toList());
    }

}
